package com.clear.subject.domain.handler.subject;

import com.alibaba.fastjson.JSON;
import com.clear.subject.common.enums.IsDeletedFlagEnum;
import com.clear.subject.common.enums.SubjectInfoTypeEnum;
import com.clear.subject.domain.convert.SubjectBriefConverter;
import com.clear.subject.domain.entity.SubjectInfoBO;
import com.clear.subject.domain.entity.SubjectOptionBO;
import com.clear.subject.infra.basic.entity.SubjectBrief;
import com.clear.subject.infra.basic.service.SubjectBriefService;
import com.google.common.base.Preconditions;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * 简答题目的策略类
 */
@Component
@Slf4j
public class BriefTypeHandler implements SubjectTypeHandler {
    @Resource
    private SubjectBriefService subjectBriefService;

    /**
     * 枚举身份的识别
     *
     * @return
     */
    @Override
    public SubjectInfoTypeEnum getHandlerType() {
        return SubjectInfoTypeEnum.BRIEF;
    }

    /**
     * 实际的题目的插入
     *
     * @param subjectInfoBO
     */
    @Override
    public void add(SubjectInfoBO subjectInfoBO) {
        // ====简答题目的插入=====
        try {
            if (log.isInfoEnabled()) {
                log.info("BriefTypeHandler.add.bo:{}", JSON.toJSONString(subjectInfoBO));
            }
            Preconditions.checkNotNull(subjectInfoBO.getSubjectAnswer(), "题目答案不能为空");

            SubjectBrief brief = SubjectBriefConverter.INSTANCE.convertBOToEntity(subjectInfoBO);
            brief.setSubjectId(subjectInfoBO.getId().intValue()); // 为每个选择设置 subject_id
            brief.setIsDeleted(IsDeletedFlagEnum.UN_DELETE.getCode());

            subjectBriefService.insert(brief);
        } catch (Exception e) {
            log.error("BriefTypeHandler.add.error:{}", e.getMessage(), e);
        }
    }

    /**
     * 查询题目详情
     *
     * @param subjectId 题目id
     */
    @Override
    public SubjectOptionBO query(int subjectId) {
        SubjectBrief subjectBrief = new SubjectBrief();
        subjectBrief.setSubjectId(subjectId);

        // 根据题目id去查
        SubjectBrief result = subjectBriefService.queryByCondition(subjectBrief);

        SubjectOptionBO subjectOptionBO = new SubjectOptionBO();
        subjectOptionBO.setSubjectAnswer(result.getSubjectAnswer());

        return subjectOptionBO;
    }
}
